<template>
  <div class="admin--page-content">
    <div v-if="isLoading" class="admin--loading">데이터를 불러오는 중...</div>
    <div v-else class="admin--form">
      <form @submit.prevent="handleSubmit">
        <table class="admin--form--table">
          <colgroup>
            <col style="width: 140px;">
            <col>
          </colgroup>
          <tbody>
            <tr>
              <th><div>아이디</div></th>
              <td>
                <div class="input--wrap">
                  <span class="admin--table-title">{{ formData.username }}</span>
                </div>
              </td>
            </tr>
            <tr>
              <th><div>이름 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.name" type="text" class="admin--form-input w--280" maxlength="30" />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>핸드폰 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <select v-model="phone1" class="admin--form-select w--120">
                    <option value="010">010</option>
                    <option value="011">011</option>
                    <option value="016">016</option>
                    <option value="017">017</option>
                    <option value="018">018</option>
                    <option value="019">019</option>
                  </select>
                  <span class="mx--8">-</span>
                  <input
                    v-model="phone2"
                    type="text"
                    inputmode="numeric"
                    class="admin--form-input w--120"
                    maxlength="4"
                    @input="onlyDigits('phone2')"
                  />
                  <span class="mx--8">-</span>
                  <input
                    v-model="phone3"
                    type="text"
                    inputmode="numeric"
                    class="admin--form-input w--120"
                    maxlength="4"
                    @input="onlyDigits('phone3')"
                  />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>이메일 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <input
                    v-model="emailLocal"
                    type="text"
                    class="admin--form-input w--160"
                    maxlength="50"
                    autocomplete="off"
                  />
                  <span class="mx--8">@</span>
                  <input
                    v-model="emailDomain"
                    type="text"
                    class="admin--form-input w--160"
                    placeholder="domain.com"
                    maxlength="50"
                    :readonly="emailDomainSelect !== 'custom'"
                    autocomplete="off"
                  />
                  <select v-model="emailDomainSelect" @change="onDomainChange" class="admin--form-select w--160 ml--8">
                    <option value="">선택</option>
                    <option value="naver.com">naver.com</option>
                    <option value="gmail.com">gmail.com</option>
                    <option value="daum.net">daum.net</option>
                    <option value="hanmail.net">hanmail.net</option>
                    <option value="kakao.com">kakao.com</option>
                    <option value="nate.com">nate.com</option>
                    <option value="custom">직접입력</option>
                  </select>
                </div>
              </td>
            </tr>
            <tr>
              <th><div>권한 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <label class="admin--radio-label" :class="{ 'is-disabled': !isSuperAdmin }">
                    <input type="radio" v-model="formData.role" value="admin" :disabled="!isSuperAdmin" />
                    관리자
                  </label>
                  <label class="admin--radio-label ml--16" :class="{ 'is-disabled': !isSuperAdmin }">
                    <input type="radio" v-model="formData.role" value="super_admin" :disabled="!isSuperAdmin" />
                    슈퍼 관리자
                  </label>
                </div>
                <p v-if="!isSuperAdmin" class="mt--10 txt--muted">권한 변경은 슈퍼 관리자만 할 수 있습니다.</p>
                <p v-else-if="formData.role === 'super_admin'" class="mt--10">슈퍼 관리자는 모든 메뉴에 접근할 수 있습니다.</p>
              </td>
            </tr>
            <tr v-if="formData.role === 'admin'">
              <th><div>메뉴 권한 <span class="admin--required">*</span></div></th>
              <td>
                <div class="admin--permissions-grid" :class="{ 'is-disabled': !isSuperAdmin }">
                  <label v-for="opt in menuOptions" :key="opt.id" class="admin--checkbox-label" :class="{ 'is-disabled': !isSuperAdmin }">
                    <input type="checkbox" :value="opt.id" v-model="formData.permissions" :disabled="!isSuperAdmin" />
                    {{ opt.title }}
                  </label>
                </div>
                <p v-if="!isSuperAdmin" class="mt--10 txt--muted">메뉴 권한 변경은 슈퍼 관리자만 할 수 있습니다.</p>
                <p v-else class="mt--10">관리자가 접근할 수 있는 메뉴를 선택하세요. 대시보드는 모든 관리자에게 기본 제공됩니다.</p>
              </td>
            </tr>
            <tr v-if="!isMyAccount">
              <th><div>상태 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <label class="admin--radio-label">
                    <input type="radio" v-model="formData.status" value="active" /> 활성
                  </label>
                  <label class="admin--radio-label ml--16">
                    <input type="radio" v-model="formData.status" value="inactive" /> 휴면
                  </label>
                  <label class="admin--radio-label ml--16">
                    <input type="radio" v-model="formData.status" value="suspended" /> 정지
                  </label>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 버튼 영역 -->
        <div class="admin--form-actions">
          <button type="button" class="admin--btn" @click="goToDetail">
            ← 취소
          </button>
          <button type="submit" class="admin--btn admin--btn-red ml--auto" :disabled="isSaving">
            {{ isSaving ? "저장 중..." : "저장" }}
          </button>
        </div>
      </form>
    </div>

    <!-- 알림 모달 -->
    <AdminAlertModal
      v-if="alertModal.show"
      :title="alertModal.title"
      :message="alertModal.message"
      :type="alertModal.type"
      @confirm="handleAlertConfirm"
      @cancel="handleAlertCancel"
      @close="closeAlertModal"
    />
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import AdminAlertModal from "~/components/admin/AdminAlertModal.vue";

  definePageMeta({
    layout: "admin",
    middleware: ["auth"],
  });

  const route = useRoute();
  const router = useRouter();
  const { get, put } = useApi();
  const { user, isSuperAdmin } = useAuth();

  const adminId = route.params.id;
  const isMyAccount = computed(() => Number(user.value?.id) === Number(adminId));

  const isLoading = ref(true);
  const isSaving = ref(false);

  const formData = ref({
    username: "",
    name: "",
    role: "admin",
    status: "active",
    permissions: [],
  });

  // 메뉴 권한 옵션 (admin.vue menuItems와 동일)
  const menuOptions = [
    { id: "admin",     title: "관리자 관리" },
    { id: "field",     title: "분야 및 지역 관리" },
    { id: "fishing",   title: "선상 및 낚시터 관리" },
    { id: "challenge", title: "챌린지 관리" },
    { id: "quest",     title: "퀘스트 관리" },
    { id: "item",      title: "아이템 관리" },
    { id: "species",   title: "어종 관리" },
    { id: "user",      title: "회원 관리" },
  ];

  // 이메일 분할
  const KNOWN_DOMAINS = ["naver.com", "gmail.com", "daum.net", "hanmail.net", "kakao.com", "nate.com"];
  const emailLocal = ref("");
  const emailDomain = ref("");
  const emailDomainSelect = ref("");
  const onDomainChange = () => {
    if (emailDomainSelect.value === "custom") {
      emailDomain.value = "";
    } else if (emailDomainSelect.value !== "") {
      emailDomain.value = emailDomainSelect.value;
    }
  };

  // 핸드폰 분할
  const phone1 = ref("010");
  const phone2 = ref("");
  const phone3 = ref("");
  const onlyDigits = (key) => {
    if (key === "phone2") phone2.value = phone2.value.replace(/\D/g, "");
    else if (key === "phone3") phone3.value = phone3.value.replace(/\D/g, "");
  };

  // 알림 모달
  const alertModal = ref({ show: false, title: "알림", message: "", type: "alert", onConfirm: null });
  const showAlert = (message, title = "알림") => {
    alertModal.value = { show: true, title, message, type: "alert", onConfirm: null };
  };
  const closeAlertModal = () => { alertModal.value.show = false; };
  const handleAlertConfirm = () => {
    if (alertModal.value.onConfirm) alertModal.value.onConfirm();
    closeAlertModal();
  };
  const handleAlertCancel = () => closeAlertModal();

  // 상세 조회 + 초기화
  const loadDetail = async () => {
    isLoading.value = true;
    const { data: res, error } = await get(`/admin/${adminId}`);
    if (error || !res?.success) {
      showAlert(error?.message || res?.message || "조회에 실패했습니다.", "오류");
      isLoading.value = false;
      return;
    }
    const row = res.data || {};

    // 일반 admin이 슈퍼관리자 수정 진입 시 차단
    if (row.role === "super_admin" && !isSuperAdmin.value) {
      isLoading.value = false;
      alertModal.value = {
        show: true,
        title: "접근 불가",
        message: "슈퍼 관리자 계정은 슈퍼 관리자만 수정할 수 있습니다.",
        type: "alert",
        onConfirm: () => router.push(`/site-manager/admin/detail/${adminId}`),
      };
      setTimeout(() => router.push(`/site-manager/admin/detail/${adminId}`), 1200);
      return;
    }

    formData.value = {
      username: row.username ?? "",
      name: row.name ?? "",
      role: row.role ?? "admin",
      status: row.status ?? "active",
      // super_admin은 "all" 문자열이 올 수 있어 배열로 통일
      permissions: Array.isArray(row.permissions) ? [...row.permissions] : [],
    };

    // 이메일 분할
    const email = row.email ?? "";
    const at = email.lastIndexOf("@");
    if (at > 0) {
      emailLocal.value = email.slice(0, at);
      emailDomain.value = email.slice(at + 1);
      emailDomainSelect.value = KNOWN_DOMAINS.includes(emailDomain.value) ? emailDomain.value : "custom";
    } else {
      emailLocal.value = "";
      emailDomain.value = "";
      emailDomainSelect.value = "";
    }

    // 핸드폰 분할 — "010-1234-5678" / "01012345678" / "010 1234 5678" 모두 처리
    const phoneRaw = String(row.phone ?? "").replace(/\D/g, "");
    if (phoneRaw.length >= 9) {
      if (phoneRaw.length === 11) {
        phone1.value = phoneRaw.slice(0, 3);
        phone2.value = phoneRaw.slice(3, 7);
        phone3.value = phoneRaw.slice(7, 11);
      } else if (phoneRaw.length === 10) {
        phone1.value = phoneRaw.slice(0, 3);
        phone2.value = phoneRaw.slice(3, 6);
        phone3.value = phoneRaw.slice(6, 10);
      }
    } else {
      phone1.value = "010";
      phone2.value = "";
      phone3.value = "";
    }

    isLoading.value = false;
  };

  // 폼 검증
  const validate = () => {
    const f = formData.value;
    const name = f.name.trim();
    if (!name) return "이름을 입력하세요.";
    if (name.length > 30) return "이름은 30자 이내";

    const local = emailLocal.value.trim();
    const domain = emailDomain.value.trim();
    if (!local) return "이메일 아이디를 입력하세요.";
    if (!domain) return "이메일 도메인을 입력하거나 선택하세요.";
    const email = `${local}@${domain}`;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return "이메일 형식이 올바르지 않습니다.";

    if (!phone1.value) return "핸드폰 앞자리를 선택하세요.";
    if (!/^\d{3,4}$/.test(phone2.value)) return "핸드폰 가운데 자리(3~4자리 숫자)를 입력하세요.";
    if (!/^\d{4}$/.test(phone3.value)) return "핸드폰 끝자리(4자리 숫자)를 입력하세요.";

    if (!["super_admin", "admin"].includes(f.role)) return "권한을 선택하세요.";
    if (!["active", "inactive", "suspended"].includes(f.status)) return "상태를 선택하세요.";

    if (f.role === "admin" && f.permissions.length === 0) {
      return "관리자에게 부여할 메뉴 권한을 1개 이상 선택하세요.";
    }

    return null;
  };

  // 폼 제출
  const handleSubmit = async () => {
    const err = validate();
    if (err) {
      showAlert(err, "입력 오류");
      return;
    }

    isSaving.value = true;
    const f = formData.value;
    const payload = {
      name: f.name.trim(),
      email: `${emailLocal.value.trim()}@${emailDomain.value.trim()}`,
      phone: `${phone1.value}-${phone2.value}-${phone3.value}`,
      status: f.status,
    };
    // role/permissions는 슈퍼관리자만 전송 (백엔드 가드와 매칭)
    if (isSuperAdmin.value) {
      payload.role = f.role;
      payload.permissions = f.role === "admin" ? f.permissions : [];
    }

    const { data, error } = await put(`/admin/${adminId}`, payload);
    isSaving.value = false;

    if (error || !data?.success) {
      showAlert(error?.message || data?.message || "수정에 실패했습니다.", "오류");
      return;
    }

    showAlert(data.message || "수정되었습니다.", "성공");
    setTimeout(() => router.push(`/site-manager/admin/detail/${adminId}`), 800);
  };

  const goToDetail = () => router.push(`/site-manager/admin/detail/${adminId}`);

  onMounted(() => {
    loadDetail();
  });
</script>
